package com.api.chatai.interceptors;

import com.api.chatai.domain.pojo.User;
import com.api.chatai.exception.myException;
import com.api.chatai.service.UserService;
import com.api.chatai.ThreadLocal.UserContextHolder;
import com.api.chatai.utils.JwtHelper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;


/*

 */
@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if ("OPTIONS".equals(request.getMethod())) {
//            System.out.println("OPTIONS请求");
            return true;
        }

        log.info("拦截器执行拦截操作......");
        String token = request.getHeader("token");
        System.out.println("token = " + token);
        String requestURI = request.getRequestURI();
        log.info("请求路径 : {}", requestURI);

        if (!StringUtils.hasText(token)) {
            throw new myException("身份信息过期,请重新登录");
        }

        Integer userId = JwtHelper.getUserId(token);


        if (userId==null) {
            throw new myException("身份信息过期,请重新登录");
        }

        User one = userService.getById(userId);
        if (one == null ) {
            throw new myException("身份信息过期,请重新登录");
        }


        UserContextHolder.setUser(one.getId());
        log.info("认证成功,当前用户 :  [  用户ID : {} ]", userId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.removeCurrentUser();
    }
}